﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using AutoProcessService.Biz;
using AutoProcessSerivce.Configuration;

namespace AutoProcessSerivce.Library.WorkPool.WorkPool.WorkHandle.Email
{
    internal abstract class BaseEmailHandle<T> : IWorkHandle<T>
    {
        string partition = string.Empty;
        protected virtual void Prepare(EmailContext ctx, string partition="account")
        {
            this.partition = partition;
            var serveritem = ConfigReader.WorkPool.EmailQueue.Pool[partition].ServerList.RandomGet();
            ctx.From = serveritem.Address;
            ctx.CredentialPassword = serveritem.Password;// System.Configuration.ConfigurationManager.AppSettings["EMail-Password"];
            ctx.CredentialUserName = serveritem.Username;// System.Configuration.ConfigurationManager.AppSettings["Email-UserName"];
        }
        protected void SendMailCallBack(EmailContext context)
        {
            if (ConfigReader.WorkPool.EmailQueue.Pool[this.partition].Enable)
            {
                new EMail(context).Send();
            }
        }

        #region IWorkHandle<T> 成员

        public abstract WaitWorkItem Process(T context);

        #endregion
    }

    internal class EmailForNormalNotifyHandle<T> : BaseEmailHandle<T>
    {
        public override WaitWorkItem Process(T context)
        {
            NormalNotifyEmail emailctx = context as NormalNotifyEmail;
            WaitWorkItem data = new WaitWorkItem();
            var ctx = new EmailContext();
            ctx.Recipient = emailctx.Recipient;
            Prepare(ctx, "notify");
            ctx.Subject = String.Format("{0} -- 学术论文云平台", emailctx.Title);
            ctx.Body = emailctx.Message;
            data.Context = ctx;

            #region 赋值Action
            data.Action = o => { SendMailCallBack(o as EmailContext); };
            #endregion

            return data;
        }
    }
    
}
